package com.imooc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imooc.entity.Book;
import com.imooc.entity.Evaluation;
import com.imooc.entity.MemberReadState;
import com.imooc.mapper.BookMapper;
import com.imooc.mapper.EvaluationMapper;
import com.imooc.mapper.MemberMapper;
import com.imooc.mapper.MemberReadStateMapper;
import com.imooc.service.BookService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service("bookService")
public class BookServiceImpl implements BookService {

    @Resource
    private BookMapper bookMapper;

    @Resource
    private MemberReadStateMapper memberReadStateMapper;

    @Resource
    private EvaluationMapper evaluationMapper;

    @Override
    public IPage<Book> paging(Long categoryId, String order, Integer page, Integer rows) {
        Page<Book> p = new Page<>(page, rows);
        QueryWrapper<Book> bookQueryWrapper = new QueryWrapper<>();
        if (categoryId != null && categoryId != -1) {
            bookQueryWrapper.eq("category_id", categoryId);
        }
        if (order != null) {
            if ("quantity".equals(order)) {
                bookQueryWrapper.orderByDesc("evaluation_quantity");
            } else if ("score".equals(order)) {
                bookQueryWrapper.orderByDesc("evaluation_score");
            }

        }
        return bookMapper.selectPage(p, bookQueryWrapper);
    }

    @Override
    public Book getById(Long bookId) {
        if (bookId != null) {
            return bookMapper.selectById(bookId);
        }
        return null;
    }

    @Override
    @Transactional
    public void updateEvaluation() {
        bookMapper.updateEvaluation();
    }

    @Override
    @Transactional
    public Book createBook(Book book) {
        bookMapper.insert(book);
        return book;
    }

    @Override
    @Transactional
    public void updateBook(Book book) {
        bookMapper.updateById(book);
    }

    @Override
    @Transactional
    public void deleteById(Long bookId) {
        bookMapper.deleteById(bookId);
        // 同时删除阅读状态和评论
        QueryWrapper<MemberReadState> readStateQueryWrapper = new QueryWrapper<>();
        readStateQueryWrapper.eq("book_id", bookId);
        memberReadStateMapper.delete(readStateQueryWrapper);
        QueryWrapper<Evaluation> evaluationQueryWrapper = new QueryWrapper<>();
        evaluationQueryWrapper.eq("book_id", bookId);
        evaluationMapper.delete(evaluationQueryWrapper);
    }
}
